import Vue from 'vue'
import Vuex from 'vuex'

import {
    setToken,
    getsToken,
    romoveToke
} from '@/utils/token.js'
import api from '@/api/index.js'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        token: getsToken() || null,
        // 登录后获取回来的用户信息
        UserInfo: null
    },
    mutations: {
        SET_TOKEN(state, value) {
            state.token = value
            //本地存储
            setToken(value)
        },
        GETUSERINFO(state, value) {
            state.UserInfo = value
        },
        LOGOUT(state, value) {
            state.UserInfo = {}
            state.token = null
            sessionStorage.removeItem("store")
            romoveToke()
        }
    },
    actions: {
        async getUserInfo({
                              commit, dispatch, state
                          }) {
            let res = await api.user.userInfo()
            //获取动态的背景颜色
            if (res.code == 200) {
                commit("GETUSERINFO", res.data)
            } else {
                romoveToke()
            }
        },
        async logout({commit, dispatch, state}) {
            let res = await api.user.logout()
            //获取动态的背景颜色
            if (res.code == 200) {
                commit("LOGOUT", res.data)
            }
        }

    },
    modules: {},
    getters: {
        isLogin(state) {
            return !!state.token;
        },
        userInfo(state) {
            return state.UserInfo;
        }
    }
})
